//
//  TwoCircleView.m
//  LightControl
//
//  Created by CKF on 2025/8/14.
//

#import "TwoCircleView.h"
#import "TimeAlertView.h"
#import "BRDatePickerView.h"
@interface TwoCircleView()
@property (nonatomic, assign) CGFloat touchAngle1;
@property (nonatomic, assign) CGFloat touchAngle2;
@property (nonatomic, assign) CGFloat startAngle;
@property (nonatomic, assign) CGFloat endAngle;
@property (nonatomic, assign) CGFloat lineWidth;
@property (nonatomic, assign) CGFloat innerMinAngle;
@property (nonatomic, strong) TimeAlertView *timeView;
@end
@implementation TwoCircleView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.startAngle = 3/4.0 * M_PI;
        self.endAngle = 1/4.0 * M_PI;
        self.touchAngle1 = self.startAngle;
        self.touchAngle2 = self.startAngle;
        self.innerMinAngle = self.startAngle-(1/360.0* M_PI);
        self.lineWidth = 14;
        
        _imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth-180, KScreenWidth-180)];
        _imgView.image = [UIImage imageNamed:@"lamp_fan"];
        _imgView.center = self.center;
        [self addSubview:_imgView];
        
        UIButton * timeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        timeBtn.frame = CGRectMake(30, frame.size.height-65, 44, 44);
        [timeBtn setImage:[UIImage imageNamed:@"Timer"] forState:0];
        timeBtn.tag = 1;
        [timeBtn addTarget:self action:@selector(timeBtnAct:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:timeBtn];
        
        
        UIImage *fanImage = [UIImage imageNamed:@"fan"];
        UIImage *fImage = [fanImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        // 3. 创建 UIImageView 并设置 tintColor
        _fanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _fanBtn.frame = CGRectMake(KScreenWidth*0.5-80, frame.size.height-65, 44, 44);
        [_fanBtn setImage:fImage forState:0];
        _fanBtn.tintColor = RGB(146, 149, 146);
        _fanBtn.tag = 2;
        [_fanBtn addTarget:self action:@selector(timeBtnAct:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_fanBtn];
        
        UIImage *lightImage = [UIImage imageNamed:@"Lightble"];
        UIImage *lImage = [lightImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        _lightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _lightBtn.frame = CGRectMake(KScreenWidth*0.5-22, frame.size.height-65, 44, 44);
//        _lightBtn.tintColor = RGB(146, 149, 146);
        _lightBtn.tintColor = RGB(43, 166, 77);
        [_lightBtn setImage:lImage forState:0];
        [_lightBtn addTarget:self action:@selector(timeBtnAct:) forControlEvents:UIControlEventTouchUpInside];
        _lightBtn.tag = 3;
        [self addSubview:_lightBtn];
        
        UIImage *alarmImage = [UIImage imageNamed:@"alarm"];
        UIImage *aImage = [alarmImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        _alarmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _alarmBtn.frame = CGRectMake(KScreenWidth*0.5+36, frame.size.height-65, 44, 44);
        _alarmBtn.tintColor = RGB(146, 149, 146);
        [_alarmBtn setImage:aImage forState:0];
        _alarmBtn.tag = 3;
        [_alarmBtn addTarget:self action:@selector(timeBtnAct:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_alarmBtn];
        
        _topLabel = [[UILabel alloc]initWithFrame:CGRectMake(KScreenWidth-110,CGRectGetMinY(timeBtn.frame)+12, 80, 16)];
        [self addSubview:_topLabel];
        _topLabel.font = [UIFont systemFontOfSize:13];
        _topLabel.textColor = RGB(146, 149, 146);
        _topLabel.textAlignment = NSTextAlignmentCenter;
        
        _bottomLabel =  [[UILabel alloc]initWithFrame:CGRectMake(KScreenWidth-110, CGRectGetMaxY(_topLabel.frame), 80, 16)];
        [self addSubview:_bottomLabel];
        _bottomLabel.font = [UIFont systemFontOfSize:13];
        _bottomLabel.textColor = RGB(146, 149, 146);
        _bottomLabel.textAlignment = NSTextAlignmentCenter;
        
        _topLabel.text = @"亮度97%";
        _bottomLabel.text = @"色温：5322K";
    }
    return self;
}

-(void)timeBtnAct:(UIButton *)btn{
//    if (btn.tag == 1) {
//        if (!_timeView) {
//            _timeView = [[TimeAlertView alloc]initWithFrame:[UIScreen mainScreen].bounds];
//            _timeView.buttonBlock = ^(NSInteger i) {
//                
//            };
//            [[UIApplication sharedApplication].delegate.window addSubview:_timeView];
//        }else{
//            _timeView.hidden = NO;
//        }
//    }
    // 1.创建日期选择器
    BRDatePickerView *datePickerView = [[BRDatePickerView alloc]init];
    // 2.设置属性
    datePickerView.pickerMode = BRDatePickerModeHM;
    datePickerView.title = LocalString(@"选择时间");
    NSDate *date = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
    NSInteger hour = [comps hour];
    NSInteger minute = [comps minute];
    // 格式化为字符串（可选）
    NSString *timeString = [NSString stringWithFormat:@"%02ld:%02ld", (long)hour, (long)minute];
    datePickerView.selectValue = timeString;
    datePickerView.isAutoSelect = false;
    datePickerView.resultBlock = ^(NSDate *selectDate, NSString *selectValue) {
        NSLog(@"选择的值：%@", selectValue);
    };
    // 设置自定义样式
    BRPickerStyle *customStyle = [[BRPickerStyle alloc]init];
    customStyle.pickerColor = BR_RGB_HEX(0xd9dbdf, 1.0f);
    customStyle.pickerTextColor = RGB(17, 17, 17);
    customStyle.separatorColor = [UIColor lightGrayColor];
    datePickerView.pickerStyle = customStyle;

    // 3.显示
    [datePickerView show];
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
    CGPoint center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
    CGFloat radius1 = MIN(CGRectGetWidth(rect), CGRectGetHeight(rect)) / 2 - 20;
    CGFloat radius2 = MIN(CGRectGetWidth(rect), CGRectGetHeight(rect)) / 2 - 60;
    
    // 绘制灰色弧线
    UIBezierPath *grayPath1 = [UIBezierPath bezierPathWithArcCenter:center radius:radius1 startAngle:self.startAngle endAngle:self.endAngle clockwise:YES];
    grayPath1.lineCapStyle = kCGLineCapRound;
    grayPath1.lineWidth = self.lineWidth;
    [RGB(142, 149, 146) setStroke];
    [grayPath1 stroke];
    
    // 绘制灰色弧线
    UIBezierPath *grayPath2 = [UIBezierPath bezierPathWithArcCenter:center radius:radius2 startAngle:self.startAngle endAngle:self.endAngle clockwise:YES];
    grayPath2.lineCapStyle = kCGLineCapRound;
    grayPath2.lineWidth = self.lineWidth;
    [RGB(142, 144, 148) setStroke];
    [grayPath2 stroke];
    
    // 绘制蓝色弧线
    UIBezierPath *bluePath = [UIBezierPath bezierPathWithArcCenter:center radius:radius1 startAngle:self.innerMinAngle endAngle:self.touchAngle1 clockwise:YES];
    bluePath.lineWidth = self.lineWidth;
    bluePath.lineCapStyle = kCGLineCapRound;
    [RGB(38, 156, 241) setStroke];
    [bluePath stroke];
    
    
//  // 绘制橘红色色弧线
    UIBezierPath *orangePath = [UIBezierPath bezierPathWithArcCenter:center radius:radius2 startAngle:self.innerMinAngle endAngle:self.touchAngle2 clockwise:YES];
    orangePath.lineWidth = self.lineWidth;
    orangePath.lineCapStyle = kCGLineCapRound;
    [RGB(255, 135, 50) setStroke];
    [orangePath stroke];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self handleTouch:touches];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self handleTouch:touches];
}

- (void)handleTouch:(NSSet<UITouch *> *)touches {
    UITouch *touch = [touches anyObject];
    if (!touch) return;
    
    CGPoint touchPoint = [touch locationInView:self];
    

    // 判断触摸点是否在弧线上
    if ([self isPointOnArcBlue:touchPoint]) {
        CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
        
        // 计算触摸点的角度
        CGFloat dx = touchPoint.x - center.x;
        CGFloat dy = touchPoint.y - center.y;
        CGFloat angle = atan2(dy, dx);
        
        // 确保角度在弧线范围内
        if (angle >= self.startAngle || angle <= self.endAngle+10/180.0*M_PI) {
            if (angle>self.endAngle && angle <= self.endAngle+10/180.0*M_PI) {
                self.touchAngle1 = self.endAngle;
            }else{
                self.touchAngle1 = angle;
            }
            [self setNeedsDisplay];
        }
    }else if ([self isPointOnArcOrange:touchPoint]) {
        CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));

        // 计算触摸点的角度
        CGFloat dx = touchPoint.x - center.x;
        CGFloat dy = touchPoint.y - center.y;
        CGFloat angle = atan2(dy, dx);

        // 确保角度在弧线范围内
        if (angle >= self.startAngle || angle <= self.endAngle+10/180.0*M_PI) {
            if (angle>self.endAngle && angle <= self.endAngle+10/180.0*M_PI) {
                self.touchAngle2 = self.endAngle;
            }else{
                self.touchAngle2 = angle;
            }
            [self setNeedsDisplay];
        }
    }else{
        NSLog(@"不在");
    }
}


- (BOOL)isPointOnArcBlue:(CGPoint)point {
    CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
    CGFloat radius = MIN(CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds)) / 2 - 20;
    // 计算触摸点到圆心的距离
    CGFloat dx = point.x - center.x;
    CGFloat dy = point.y - center.y;
    CGFloat distance = sqrt(dx * dx + dy * dy);
    
    float number = fabs(distance - radius);
    NSLog(@"number------%f",number);
    // 检查距离是否在弧线宽度范围内
    BOOL isInDistanceRange = number <= self.lineWidth / 2;
    // 计算触摸点的角度
    CGFloat angle = atan2(dy, dx);
    
    // 确保角度在弧线范围内
    BOOL isInAngleRange = angle >= self.startAngle || angle <= (self.endAngle+(10/180.0*M_PI));
    
    return isInDistanceRange && isInAngleRange;
}

- (BOOL)isPointOnArcOrange:(CGPoint)point {
    CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
    CGFloat radius = MIN(CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds)) / 2 - 60;
    // 计算触摸点到圆心的距离
    CGFloat dx = point.x - center.x;
    CGFloat dy = point.y - center.y;
    CGFloat distance = sqrt(dx * dx + dy * dy);

    float number = fabs(distance - radius);
    NSLog(@"number------%f",number);
    // 检查距离是否在弧线宽度范围内
    BOOL isInDistanceRange = number <= self.lineWidth / 2;
    // 计算触摸点的角度
    CGFloat angle = atan2(dy, dx);

    // 确保角度在弧线范围内
    BOOL isInAngleRange = angle >= self.startAngle || angle <= self.endAngle+10/180.0*M_PI;

    return isInDistanceRange && isInAngleRange;
}

@end
